<?php
/* 
 * class.list.php
 * 商家列表类
 * @version 0.1
 * @author samuel
 * @date 2009-05-07
 */
include_once 'class.sellerBase.php';
class seller_list extends sellerBase {
    private $step;
    private $classname;
    private $tpl_file;

    function  __construct($core) {
        parent::__construct();

        //参数处理
        $this->step = $this->params['step'];
        if(!$this->step) $this->step = "list";
        $this->classname = strtolower(trim(get_class($this)));
        $this->tpl_file = $this->classname . "_" . $this->step . ".html";

        $this->run();
    }

    function run(){
        //var_dump($this->step);
        switch($this->step){
            case 'list':
                $page = is_numeric($this->params['page']) ? $this->params['page'] : 1;
                $pagesize = 20;
                $current_url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'];
                $arr_limit = array('page'=>$page, 'pagesize'=>$pagesize, 'url'=>$current_url);
                $arr_sellers_info = $this->getSellerList("", array("SellerID"=>"desc"), $arr_limit);
                $arr_sellers = $arr_sellers_info['list'];
                $pager = $arr_sellers_info['pager'];
                $this->core->tpl->assign('arr_sellers', $arr_sellers);
                $this->core->tpl->assign('pager', $pager);
                break;
            case 'add':
                $this->getSellerCates(0, $cates);
				$this->core->tpl->assign('cates', $cates);
                $provinces = $this->getSellerAllProvinceList();
				$this->core->tpl->assign('provinces', $provinces);
                $cities = $this->getSellerAllCityList();
				$this->core->tpl->assign('cities', $cities);
                $cbds = $this->getSellerAllCBDList();
				$this->core->tpl->assign('cbds', $cbds);
                break;
            case 'do_add':
				$seller = array();
                $seller['SellerSn'] = $this->params['SellerSn'];
                $seller['SellerNo'] = $this->params['SellerNo'];
				$seller['SellerNameCN'] = $this->params['SellerNameCN'];
				$seller['SellerClassID'] = $this->params['SellerClassID'];
				$seller['SellerLogoUrl'] = $this->params['SellerLogoUrl'];
				$seller['SellerProvinceID'] = $this->params['SellerProvinceID'];
				$seller['SellerCityID'] = $this->params['SellerCityID'];
				$seller['SellerCBDID'] = $this->params['SellerCBDID'];
				$seller['SellerType'] = $this->params['SellerType'];
				$seller['SellerAddress'] = $this->params['SellerAddress'];
				$seller['SellerTel'] = $this->params['SellerTel'];
				$seller['SellerTel_z'] = $this->params['SellerTel_z'];
				$seller['SellerTime'] = $this->params['SellerTime'];
				$seller['SellerTraffic'] = $this->params['SellerTraffic'];
				$seller['SellerSign'] = $this->params['SellerSign'];
				$seller['SellerRecommend'] = $this->params['SellerRecommend'];
				$seller['SellerConsume'] = $this->params['SellerConsume'];
				$seller['SellerOther'] = $this->params['SellerOther'];

                $tag = $this->addNewSeller($seller);
                if(!$tag){
                    $this->core->utility->messagePrompt($this->error);
                }
                $this->core->utility->messagePrompt('添加成功!');
                return;
                break;
            case 'edit':
				$this->getSellerCates(0, $cates);
				$this->core->tpl->assign('cates', $cates);
                $provinces = $this->getSellerAllProvinceList();
				$this->core->tpl->assign('provinces', $provinces);
                $cities = $this->getSellerAllCityList();
				$this->core->tpl->assign('cities', $cities);
                $cbds = $this->getSellerAllCBDList();
				$this->core->tpl->assign('cbds', $cbds);

                $sid = $this->params['sid'];
                $seller = $this->getSellerInfo($sid);
				$this->core->tpl->assign('seller', $seller);
                break;
			case 'do_edit':
				$sid = $this->params['sid'];
				$seller = array();
                $seller['SellerSn'] = $this->params['SellerSn'];
                $seller['SellerNo'] = $this->params['SellerNo'];
				$seller['SellerNameCN'] = $this->params['SellerNameCN'];
				$seller['SellerClassID'] = $this->params['SellerClassID'];
				$seller['SellerLogoUrl'] = $this->params['SellerLogoUrl'];
				$seller['SellerProvinceID'] = $this->params['SellerProvinceID'];
				$seller['SellerCityID'] = $this->params['SellerCityID'];
				$seller['SellerCBDID'] = $this->params['SellerCBDID'];
				$seller['SellerType'] = $this->params['SellerType'];
				$seller['SellerAddress'] = $this->params['SellerAddress'];
				$seller['SellerTel'] = $this->params['SellerTel'];
				$seller['SellerTel_z'] = $this->params['SellerTel_z'];
				$seller['SellerTime'] = $this->params['SellerTime'];
				$seller['SellerTraffic'] = $this->params['SellerTraffic'];
				$seller['SellerSign'] = $this->params['SellerSign'];
				$seller['SellerRecommend'] = $this->params['SellerRecommend'];
				$seller['SellerConsume'] = $this->params['SellerConsume'];
				$seller['SellerOther'] = $this->params['SellerOther'];
				$this->updateInfo('fun_seller', 'SellerID', $sid, $seller);
				if($this->error){
					$this->core->utility->messagePrompt($this->error);
				}else{
					$this->core->utility->messagePrompt('更新成功！');
				}
				return;
				break;
			case 'del':
				$sid = $this->params['sid'];
                $del['del'] = 1;
				$this->updateInfo('fun_seller', 'SellerID', $sid, $del);
				if($this->error){
					$this->core->utility->messagePrompt($this->error);
				}else{
					$this->core->utility->messagePrompt('删除成功！');
				}
				return;
				break;
			case 'batch_del':
                $ids = $this->params['checkboxes'];
                if(is_array($ids)){
                    foreach($ids as $id){
                        $del['del'] = 1;
                        $this->updateInfo('fun_seller', 'SellerID', $id, $del);
                    }
                }
                if($this->error){
					$this->core->utility->messagePrompt($this->error);
				}else{
					$this->core->utility->messagePrompt('删除成功！');
				}
                return;
                break;
			case 'search':
				$search_name = $this->params['search_catename'];
				$search_pname = $this->params['search_pcatename'];
				$search_url_append = "&step=".$this->step."&search_catename=".$search_name."&search_pcatename=".$search_pname;
				$arr_filter = array();
				if($search_name){
					$arr_filter[] = array('attr'=>'SellerClassName', 'value'=>$search_name, 'match'=>'like');
				}
				if($search_pname){
					$arr_filter[] = array('attr'=>'SellerClassName', 'value'=>$search_pname, 'match'=>'like', 'join'=>'b');
				}
				$page = is_numeric($this->params['page']) ? $this->params['page'] : 1;
                $pagesize = 20;
                $current_url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] . $search_url_append;
                $arr_limit = array('page'=>$page, 'pagesize'=>$pagesize, 'url'=>$current_url);
                $arr_cates_info = $this->getSellerCateList($arr_filter, array("SellerClassID"=>"desc"), $arr_limit);
                $arr_cates = $arr_cates_info['list'];
                $pager = $arr_cates_info['pager'];
                $this->core->tpl->assign('arr_cates', $arr_cates);
                $this->core->tpl->assign('pager', $pager);
				//共用一个模板
				$this->tpl_file = "seller_cate_list.html";
				break;
            case 'ajax_getcity':
                $pid = $this->params['pid'];
                $cities = $this->getSellerAllCityList($pid);
                echo json_encode($cities);
                return;
                break;
            case 'ajax_getcbd':
                $cid = $this->params['cid'];
                $cbds = $this->getSellerAllCBDList($cid);
                echo json_encode($cbds);
                return;
                break;
            case 'excel_upload':
                //var_dump(spl_autoload_unregister('__autoload'));
                @set_time_limit(300);
                if (!is_uploaded_file($_FILES['excel_upload']['tmp_name'])) {
                   echo "非法途径上传的文件！";
                   return false;
                } else {
                    //文件后缀名
                    $suffix = strtolower(trim($this->getFileSuffix( $_FILES['excel_upload']['name'] )));
                    if(strtolower($_FILES['excel_upload']['type']) == 'application/vnd.ms-excel' || $suffix == 'xls' || $suffix == 'xlsx' || $suffix == 'xlsb'){
                        @ini_set('memory_limit', '128M');
                        $excel_path = CLASS_PATH . "excel/";
                        @set_include_path(get_include_path() . PATH_SEPARATOR . $excel_path);
                        include_once 'PHPExcel/IOFactory.php';
                        $objPHPExcel = PHPExcel_IOFactory::load($_FILES['excel_upload']['tmp_name']);
                        //$objPHPExcel_worksheet = $objPHPExcel->getSheet(2);
                        //var_dump($objPHPExcel->getSheet(2));
                        //$objReader = PHPExcel_IOFactory::createReader('Excel2007');
                        //$objReader->setReadDataOnly(true);
                        //$objPHPExcel = $objReader->load($_FILES['excel_upload']['tmp_name']);
                        $objWorksheet = $objPHPExcel->getSheet(1);
                        $highestRow = $objWorksheet->getHighestRow();
                        $highestColumn = $objWorksheet->getHighestColumn();
                        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
                        //获取列所对应的数据字段名
                        $db_fields = array();
                        for ($col = 0; $col <= $highestColumnIndex; $col++) {
                            $tmp_colname = $objWorksheet->getCellByColumnAndRow($col, 1)->getValue();
                            //var_dump($tmp_colname);
                            $db_fields[] = $this->getExcelColField($tmp_colname);
                        }
                        //导入每行数据
                        for ($row = 2; $row <= $highestRow; $row++) {
                            $append_sql = "";
                            $arr_append_sql = array();
                            var_dump("============================");
                            for ($col = 0, $k=0; $col <= $highestColumnIndex; $col++, $k++) {
                                $tmp_data = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                                //var_dump($tmp_data);
                                $field = $db_fields[$k];
                                $this->build_insert_sql($field, $tmp_data, $arr_append_sql);
                            }
                            $append_sql = implode(',', $arr_append_sql);
                            $sql = "INSERT INTO `fun_seller` SET " . $append_sql . " , `SellerCreatTime`=now()";
                            echo $sql,"<br/>";
                            $this->core->db->query($sql); 
                        }

                    }else{
                        $this->core->utility->messagePrompt('对不起，您上传的不是一个合法的Excel文档!');
                        return;
                    }
                }
                return;
                break;
        }
        $this->core->tpl->display($this->tpl_file);
    }

    /**
	* 函数说明：获取文件名后缀
	*/
	private function getFileSuffix( $file_name ){
		$retval = "";
		$pt = strrpos($file_name, ".");
		if ($pt) $retval = substr($file_name, $pt+1, strlen($file_name) - $pt);
		return ($retval);
	}

	/**
	 * 获取EXCEL列对应的数据表字段
	 */
	private function getExcelColField($col){
		$col = trim($col);
		$arr_field = array();
		$arr_field['SellerSn'] = '商家编号';
		$arr_field['SellerNameCN'] = '商家名称';
		$arr_field[''] = '所属片区';
		$arr_field['SellerCBDID'] = '商圈';
		$arr_field['SellerClassID'] = '商家类别';
		$arr_field['SellerAddress'] = '地址';
		$arr_field['SellerTel'] = '电话';
		$arr_field['SellerTime'] = '营业时间';
		$arr_field['SellerTraffic'] = '乘车指南';
		$arr_field['SellerSign'] = '醒目标识';
		$arr_field[''] = '优惠信息';
		$arr_field['SellerRecommend'] = '特色产品（含图片）';
		$arr_field[''] = '实景照片';
		$arr_field['SellerOther'] = '其他信息';
		$arr_field['SellerConsume'] = '消费指数';

		$field = array_search($col, $arr_field);
		return $field;
	}

	/**
	 * 构造SQL语句
	 */
	private function build_insert_sql($field, $value, &$arr_sql){
		$field = trim($field);
		if(!$field) return;
		switch($field){
			case 'SellerCBDID':
				$arr_ids = $this->getCBDIDByName($value);
                $cbdid = $arr_ids['cbdid'];
				$arr_sql[] = " `".$field."`='".$cbdid."'";
                $cityid = $arr_ids['cityid'];
                $provinceid = $arr_ids['provinceid'];
                $arr_sql[] = " `SellerProvinceID`='".$provinceid."'";
                $arr_sql[] = " `SellerCityID`='".$cityid."'";
				break;
			case 'SellerClassID':
                $arr_values = explode(',', $value);
                $arr_cids = "";
                foreach($arr_values as $v){
                    $cid = $this->getCIDByCname($v);
                    $arr_cids[] = $cid;
                }
                $str_cids = implode(',', $arr_cids);
				
				$arr_sql[] = " `".$field."`='".$str_cids."'";
				break;
			default:
				$arr_sql[] = " `".$field."`='".$value."'";
		}
	}

	/**
	 * 获取商圈ID
	 * @param <type> $name
	 * @return <type>
	 */
	private function getCBDIDByName($name){
		$sql = "SELECT `SellerCBDID` FROM `fun_seller_cbd` WHERE `SellerCBDNameCN`='".$name."'";
		$id = $this->core->db->get_var($sql);
        if($id){
            $cid = $this->getCityIDByCBD($id);
            $pid = $this->getProvinceIDByCityID($cid);
        }
		return array('cbdid'=>$id, 'cityid'=>$cid, 'provinceid'=>$pid);
	}
    
    private function getCityIDByCBD($cid){
        $sql = "SELECT `SellerCityID` FROM `fun_seller_cbd` WHERE `SellerCBDID`='".$cid."'";
        $id = $this->core->db->get_var($sql);
        return $id;
    }

    private function getProvinceIDByCityID($cid){
        $sql = "SELECT `SellerProvinceID` FROM `fun_seller_city` WHERE `SellerCityID`='".$cid."'";
		$id = $this->core->db->get_var($sql);
		return $id;
    }

	private function getCIDByCname($name){
		$sql = "SELECT `SellerClassID` FROM `fun_seller_class` WHERE `SellerClassName`='".$name."'";
		$id = $this->core->db->get_var($sql);
		return $id;
	}
}
?>